﻿/*
Copyright © 2011 François Karman

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

See <license.txt> for the complete license of the software.
*/

using System;
using System.Collections.Generic;

namespace Simple.Storage.Api
{
    /// <summary>
    /// Implements  the <see cref="IInitializer"/> interface for the basic types and the default
    /// serialization behaviors.
    /// </summary>
    public class DefaultInitializer : Initializable, IInitializer
    {
        /// <summary>
        /// The serializers shared by all the data sources created with this initializer.
        /// </summary>
        private readonly ICollection<ISerializer> shared;

        /// <summary>
        /// The methods used to create extended serializers.
        /// </summary>
        private readonly ICollection<Func<IGroupedSerializer, ISerializer>> extendedCreators;

        /// <summary>
        /// Initializes a new instance of the DefaultInitializer class.
        /// </summary>
        public DefaultInitializer()
            : base()
        {
            this.shared = new LinkedList<ISerializer>();
            this.extendedCreators = new LinkedList<Func<IGroupedSerializer, ISerializer>>();
        }

        /// <summary>
        /// Adds serializers to a provided group.
        /// </summary>
        /// <param name="datasource">
        /// The initialized data source.
        /// </param>
        /// <param name="serializers">
        /// The serializers used for the properties of the <paramref name="datasource"/>.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// One of the parameters is <c>null</c>.
        /// </exception>
        public void CreateSerializers(IDataSource datasource, IGroupedSerializer serializers)
        {
            if (datasource == null)
            {
                throw new ArgumentNullException("datasource");
            }
            else if (serializers == null)
            {
                throw new ArgumentNullException("serializers");
            }

            this.Initialize();

            foreach (ISerializer serializer in this.shared)
            {
                serializers.Add(serializer);
            }

            foreach (Func<IGroupedSerializer, ISerializer> creator in this.extendedCreators)
            {
                serializers.Add(creator.Invoke(serializers));
            }
        }

        /// <summary>
        /// Creates a serializer used for the links with a specified persisted class.
        /// </summary>
        /// <param name="datasource">The initialized data source.</param>
        /// <param name="definition">The definition of the linked elements.</param>
        /// <param name="propertySerializer">The serializer used for properties.</param>
        /// <returns>The serializer used to serialize the links of the <paramref name="definition"/> class.</returns>
        public ISerializer CreateLinkSerializer(IDataSource datasource, IClassDefinition definition, ISerializer propertySerializer)
        {
            this.Initialize();
            return new LinkSerializer(datasource, definition, propertySerializer);
        }

        /// <summary>
        /// Creates a serializer used for the instance of a specified persisted class.
        /// </summary>
        /// <param name="datasource">The initialized data source.</param>
        /// <param name="definition">The definition of the serialized instances.</param>
        /// <param name="propertySerializer">The serializer used for properties.</param>
        /// <returns>The serializer used to serialize the instances of the <paramref name="definition"/> class.</returns>
        public ISerializer CreateClassSerializer(IDataSource datasource, IClassDefinition definition, ISerializer propertySerializer)
        {
            this.Initialize();

            // Test the datasource to onform to the contract - This is done
            // after the call to initialize to be consistant with others parameters
            if (datasource == null)
            {
                throw new ArgumentNullException("datasource");
            }

            return new ClassSerializer(definition, propertySerializer);
        }

        /// <summary>
        /// Adds a new basic serializer as part of the shared serializers.
        /// </summary>
        /// <param name="serializer">The new serializer.</param>
        /// <returns>The current initializer.</returns>
        /// <exception cref="AlreadyInitializedException">
        /// The initializer has already been used and can't be modified.
        /// </exception>
        public DefaultInitializer AddSerializer(ISerializer serializer)
        {
            this.AssertNotInitialized();
            this.shared.Add(serializer);
            return this;
        }

        /// <summary>
        /// Initializes the current instance.
        /// </summary>
        protected override void InternalInitialize()
        {
            // Initialize the basic serializers
            this.shared.Add(new Serializer.BoolSerializer());
            this.shared.Add(new Serializer.ByteSerializer());
            this.shared.Add(new Serializer.CharSerializer());
            this.shared.Add(new Serializer.DecimalSerializer());
            this.shared.Add(new Serializer.DoubleSerializer());
            this.shared.Add(new Serializer.Int16Serializer());
            this.shared.Add(new Serializer.Int32Serializer());
            this.shared.Add(new Serializer.Int64Serializer());
            this.shared.Add(new Serializer.SByteSerializer());
            this.shared.Add(new Serializer.SingleSerializer());
            this.shared.Add(new Serializer.StringSerializer());
            this.shared.Add(new Serializer.UInt16Serializer());
            this.shared.Add(new Serializer.UInt32Serializer());
            this.shared.Add(new Serializer.UInt64Serializer());
            this.shared.Add(new Serializer.DateTimeSerializer());
            this.shared.Add(new Serializer.GuidSerializer());
            this.shared.Add(new Serializer.TimeSpanSerializer());
            this.shared.Add(new Serializer.UriSerializer());

            // Initialize the extended serializers
            this.extendedCreators.Add(s => new Serializer.ArraySerializer(s));
            this.extendedCreators.Add(s => new Serializer.CollectionSerializer(s));
        }
    }
}
